<template>
	<div class="container">
		<div id="exit-info-page">
			<a-descriptions title="出场记录" bordered size="middle">
				<template #extra>
					<div><b>验收单编号：</b> {{ route.query.code }}</div>
					<div><b>发货单编号：</b> {{ formState.code }}</div>
				</template>
				<!--        <a-descriptions-item label="验收单信息" :span="3"></a-descriptions-item>-->
				<a-descriptions-item label="项目名称">{{ project.name??'' }}</a-descriptions-item>
				<a-descriptions-item label="供应商名称" :span="2">{{ supplier.company_name??'' }}</a-descriptions-item>
				<a-descriptions-item label="接收人/电话">{{ formState.receiver }} / {{ formState.receiver_tel }}</a-descriptions-item>
				<a-descriptions-item label="收货地址" :span="2">{{ formState.deliver_address }}</a-descriptions-item>
				<a-descriptions-item label="验收类型">{{ yslist.find((d) => d.value === formState.ys_type)?.label }}</a-descriptions-item>
				<a-descriptions-item label="验收人" :span="2">
					<template v-if="formState.ys_settings?.length">
						<span v-for="(item, index) in formState.ys_settings" :key="index">
							<template v-if="item.ys_status === 2">
								<template v-if="item.opr?.manually_signed_file_path">
									<a-image :width="60" :src="item.opr?.manually_signed_file_path" />
								</template>
								<template v-else>
									<span style="padding: 0 5px;">{{ item.opr?.fullname }}</span>
								</template>
							</template>
						</span>
					</template>
					<template v-else>
						<template v-if="formState.yanshouLog?.opr?.manually_signed_file_path">
							<a-image :width="60" :src="formState.yanshouLog.opr?.manually_signed_file_path" />
						</template>
						<template v-else>
							{{ formState.yanshouLog?.opr?.fullname }}
						</template>
					</template>
				</a-descriptions-item>
			</a-descriptions>
			<br />
			<a-row :gutter="20">
				<a-col :span="24">
					<a-table :pagination="false" :data-source="formState.materials" :columns="purchaseColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, index, record }">
							<template v-if="column.dataIndex === 'exit_quantity'">
								<a-form-item :name="['materials', index, 'exit_quantity']">
									<a-input v-model:value="record.exit_quantity" type="number" min="1" placeholder="出场物料数" @change="checkExitQuantity(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']">
									<a-input v-model:value="formState.materials[index].use_time" type="number" min="1" placeholder="请输入使用时长" />
								</a-form-item>
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>
			<div style="text-align: right;padding-top: 5px;"><b>验收时间：</b> {{ formState.yanshouLog?.create_time }}</div>
			<div>
				<a-row v-if="realFileList?.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="发货附件" name="real_pic_path">
							<template v-for="item in realFileList" :key="item.url">
								<a target="_blank" :href="item.url">{{ item.name }}</a><br />
							</template>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row v-if="realPicList?.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="发货图片" name="real_pic_path"></a-form-item>
					</a-col>
					<a-col v-for="item in realPicList" :key="item.url" :span="4">
						<div class="gallery-image">
							<a-image :width="160" :height="160" :src="item.url" />
						</div>
						<p>{{ item.name }}</p>
					</a-col>
				</a-row>
				<a-row v-if="formState.pic_path?.length && !approvedHistory.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="验收图片" name="pic_path"></a-form-item>
					</a-col>
					<a-col v-for="item in formState.pic_path" :key="item.url" :span="4">
						<div class="gallery-image">
							<a-image :width="160" :height="160" :src="item.url" />
						</div>
						<p>{{ item.name }}</p>
					</a-col>
				</a-row>
				<a-row v-if="formState.video_path?.length && !approvedHistory.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="验收视频" name="video_path"></a-form-item>
					</a-col>
					<a-col v-for="item in formState.video_path" :key="item.url" :span="4">
						<div class="gallery-image">
							<video controls :width="160" :height="160">
								<source :src="item.url" type="video/mp4" />
							</video>
						</div>
						<p>{{ item.name }}</p>
					</a-col>
				</a-row>
				<a-row v-if="approvedHistory.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="验收图片" name="pic_path"></a-form-item>
					</a-col>
					<template v-for="item in approvedHistory" :key="item.id">
						<template v-if="item.pic_path && item.pic_path !== '[]'">
							<a-col v-for="i in JSON.parse(item.pic_path)" :key="i.url" :span="4">
								<div class="gallery-image">
									<a-image :width="160" :height="160" :src="i.url" />
								</div>
								<p>{{ i.name }}</p>
							</a-col>
						</template>
					</template>
				</a-row>
				<a-row v-if="approvedHistory.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="验收视频" name="pic_path"></a-form-item>
					</a-col>
					<template v-for="item in approvedHistory" :key="item.id">
						<template v-if="item.video_path && item.video_path !== '[]'">
							<a-col v-for="i in JSON.parse(item.video_path)" :key="i.url" :span="4">
								<video controls :width="160" :height="160">
									<source :src="i.url" type="video/mp4" />
								</video>
							</a-col>
						</template>
					</template>
				</a-row>
				<a-tabs v-model:activeKey="activeTab">
					<a-tab-pane key="exit_history" tab="出场记录">
						<a-table :pagination="false" :data-source="formState.exitOrders" :columns="exitColumns" :row-key="(record) => record.id">
							<template #expandedRowRender="{ index }">
								<a-table :pagination="false" :data-source="formState.exitOrders[index]?.materials" :columns="exitMaterialColumns" :row-key="(record) => record.id">

								</a-table>
							</template>
						</a-table>
					</a-tab-pane>
					<a-tab-pane key="ys_history" tab="验收记录">
						<a-descriptions>
							<template v-for="item in approvedHistory" :key="item.id">
								<a-descriptions-item label="验收时间">{{ item.update_time }}</a-descriptions-item>
								<a-descriptions-item label="验收人">
									<template v-if="item.opr?.manually_signed_file_path">
										<a-image :width="60" :src="item.opr?.manually_signed_file_path" />
									</template>
									<template v-else>
										<span style="padding: 0 5px;">{{ item.opr?.fullname }}</span>
									</template>
									<span v-if="item.opr.is_consignor">({{ item.opr?.parent_user?.company_name }})</span>
								</a-descriptions-item>
								<a-descriptions-item label="验收描述">{{ item.ys_des }}</a-descriptions-item>
							</template>
						</a-descriptions>
					</a-tab-pane>
				</a-tabs>
			</div>
		</div>
		<a-row :gutter="20">
			<a-col :span="24" class="py-4 text-center">
				<a-space>
					<a-button v-permission="266" type="primary" @click="handleSave">
						<save-outlined />出场确认
					</a-button>
					<a-button @click="closeTab('/exit/order/list')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { Modal } from "ant-design-vue";
import { DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { post, postJson, treeToList } from "../utils";
import { useRoute } from "vue-router";
import dayjs from "dayjs";
import { userStore } from "@/store/index.js";
import { add, subtract } from "../utils/operation.js";

const store = userStore();
const userInfo = store.info;
const route = useRoute();
const formState = ref({ materials: [] });
const approvedHistory = ref([]);
const formRef = ref();
const realFileList = ref([]);
const realPicList = ref([]);
const { proxy } = getCurrentInstance();
const yslist = [
	{ value: 1, label: "钢筋" },
	{ value: 2, label: "混凝土" },
	{ value: 3, label: "周转材料" },
	{ value: 4, label: "机械" },
	{ value: 5, label: "其它" },
	{ value: 6, label: "辅助材料" }
];

const appraise = ref(route.query.appraise);

const purchaseColumns = ref([
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			let value = text;
			if (formState.value.ys_type === 2) {
				value = 'm³';
			}
			return value;
		}
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return contracts.value.find((d) => d.id === text)?.name;
		}
	},
	{
		title: "采购数量",
		dataIndex: "quantity",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text || record.fangliang;
		}
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		align: "center"
	},
	{
		title: "进场时间",
		dataIndex: "enter_time",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "出场余量",
		dataIndex: "exit_surplus_quantity",
		width: 130,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return subtract([record.ys_quantity, record.SupplyOrderMaterial?.exit_quantity], 3);
		}
	},
	{
		title: "出场数量",
		dataIndex: "exit_quantity",
		width: 130,
		align: "center",
	},
	{
		title: "使用时长",
		dataIndex: "use_time",
		width: 130,
		align: "center"
	},
	{
		title: "工号",
		dataIndex: "use_position",
		align: "center"
	},
	{
		title: "预计浇筑部位",
		dataIndex: "predict_position",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.expected_location;
		}
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
]);

const exitColumns = [
	{
		title: "ID",
		dataIndex: "id",
		width: 60,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: "出场时间",
		dataIndex: "create_time",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "出场人",
		dataIndex: "opr",
		customRender: ({ text, record, index, column }) => {
			return text.fullname;
		}
	},
	{
		title: "出场物料总数",
		dataIndex: "materials",
		customRender: ({ text, record, index, column }) => {
			return add(text.map(item => item.exit_quantity), 3);
		}
	},
	{
		title: "使用总时长",
		dataIndex: "materials",
		customRender: ({ text, record, index, column }) => {
			return add(text.map(item => item.exit_time), 2);
		}
	}
]
const exitMaterialColumns = [
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			let value = text;
			if (formState.value.ys_type === 2) {
				value = 'm³';
			}
			return value;
		}
	},
	{
		title: "出场数量",
		dataIndex: "exit_quantity",
		align: "center",
	},
	{
		title: "使用时长",
		dataIndex: "exit_time",
		align: "center"
	},
]

// 物资信息
const purchaseOrderInfo = ref({});
const project = ref({});
const supplier = ref({});
const contracts = ref([]);

const id = computed(() => route.params.id);
const type = ref();
const activeTab = ref('exit_history')
onMounted(() => {
	post(`exitOrder/info`, { id: id.value }).then(async data => {
		data.pic_path = JSON.parse(data.pic_path || "[]");
		data.video_path = JSON.parse(data.video_path || "[]");
		data.real_pic_path = JSON.parse(data.real_pic_path || "[]");
		for (const file of data.real_pic_path) {
			const suffix = file.url?.split(".").pop();
			if (['jpg', 'jpeg', 'png'].includes(suffix)) {
				realPicList.value.push(file)
			} else {
				realFileList.value.push(file);
			}
		}
		// 非机械和混凝土没有使用部位栏位
		if (![2].includes(data.ys_type)) {
			purchaseColumns.value = purchaseColumns.value.filter((item) => item.dataIndex !== 'use_position' && item.dataIndex !== 'predict_position');
		}
		contracts.value = await post("contract/all", { supplier_id: data.supplier_id, project_id: data.project_id });
		const gonghaoList = treeToList(await post("department/getTrees", { type: 4, parent_id: data.project_id }), []);
		data.materials = data.materials.map(item => {
			const { quantity, unit, memo, use_date, time_unit, fangliang, luodu, changdu, add_time, part, real_quantity, ys_quantity, enter_time, exit_time, position, gonghao_id, expected_location, contract_id } = item.SupplyOrderMaterial;
			let use_position = '';
			if (gonghao_id) {
				use_position += gonghaoList.filter((i) => {
					return i.id === gonghao_id
				})[0]?.name || ''
			}
			if (position) {
				use_position += gonghaoList.filter((i) => {
					return i.id === position
				})[0]?.name || ''
			}
			return {
				...item,
				quantity,
				unit,
				memo,
				use_position,
				position,
				use_date,
				time_unit,
				fangliang,
				luodu,
				changdu,
				part,
				real_quantity,
				ys_quantity,
				enter_time,
				exit_time,
				add_time: dayjs(add_time).format("YYYY-MM-DD HH:mm:ss"),
				expected_location,
				contract_id,
				use_time: dayjs(dayjs().format('YYYY-MM-DD')).diff(dayjs(enter_time).format('YYYY-MM-DD'), 'day') + 1,
				exit_quantity: null,
			};
		});
		type.value = data.purchaseOrder.type;
		const purchaseOrder = data.purchaseOrder;
		purchaseOrder.create_time = dayjs(purchaseOrder.create_time).format("YYYY-MM-DD HH:mm:ss");
		purchaseOrderInfo.value = purchaseOrder;
		project.value = data.project;
		supplier.value = data.supplier;
		data.ys_type = parseInt(data.ys_type);
		Object.assign(data, data.appraise);
		formState.value = data;
		approvedHistory.value = formState.value.ys_settings.filter((item) => item.ys_status === 2);
		// 只有周转材料 和 机械 才需要显示[出场时间, 使用时长, 时长单位]
		if (![3, 4].includes(data.ys_type)) {
			purchaseColumns.value = purchaseColumns.value.filter(item => {
				return !["exit_time", "use_time", "time_unit"].includes(item.dataIndex);
			});
		}
	});
});
const checkExitQuantity = (record) => {
	if (record.exit_quantity > subtract([record.ys_quantity, record.SupplyOrderMaterial?.exit_quantity], 3)) {
		proxy.$message.error("出场数量不得大于余量");
		record.exit_quantity = subtract([record.ys_quantity, record.SupplyOrderMaterial?.exit_quantity], 3)
	}
}
const closeTab = inject("closeTab");
const handleSave = () => {
	const params = formState.value.materials.map(item => {
		return {
			id: item.id,
			use_time: Number(item.use_time) || 0,
			exit_quantity: Number(item.exit_quantity) || 0,
		}
	}).filter(item => item.use_time > 0 && item.exit_quantity > 0);
	if (!params.length) {
		proxy.$message.error("请至少操作一个物料");
		return;
	}
	Modal.confirm({
		title: "操作确认?",
		content: "您确定要出场吗，请确认",
		onOk() {
			postJson("exitOrder/save", {
				supply_order_id: id.value,
				project_id: formState.value.project_id,
				materials: params,
			}).then(data => {
				proxy.$message.success("保存成功");
				closeTab('/exit/order/list');
			}).catch(err => {
				proxy.$message.error(err);
			});
		}
	})
}
</script>

<style scoped lang="scss">
.container {
  background: #fff;
  padding: 20px;

  :deep(.ant-table-cell) .ant-form-item {
    margin-bottom: 0;

    .ant-form-item-explain {
      position: absolute;
      bottom: -24px;
    }
  }
}

:deep(.ant-input[disabled]) {
  color: rgba(0, 0, 0, 0.65);
  background: #fff;
  border: 1px solid #d9d9d9;
}
:deep(.ant-input-disabled) {
  color: rgba(0, 0, 0, 0.65);
  background: #fff;
  border: 1px solid #d9d9d9;
}
//
:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
  color: rgba(0, 0, 0, 0.65);
  background: #fff;
  border: 1px solid #d9d9d9;
}
:deep(.ant-radio-disabled + span) {
  color: rgba(0, 0, 0, 0.65);
  background: #fff;
}

.gallery {
  display: flex;
  flex-wrap: wrap;

  & > div {
    margin: 0 15px 15px 0;
    overflow: hidden;
    width: 160px;

    p {
      line-height: 20px;
      height: 20px;
      overflow: hidden;
      margin: 8px 0;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.gallery-image {
  display: inline-block;
  width: 160px;
  height: 160px;
  overflow: hidden;
  padding:0 5px;
}
:deep(.ant-descriptions-title) {
  text-align: center;
}
#exit-info-page {
  padding-top: 40px;
  position: relative;
}
</style>
